package com.cays.myresearch.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.cays.myresearch.R;
import com.cays.myresearch.Util.HttpUtil;
import com.cays.myresearch.action.LoginAction;
import com.cays.myresearch.adapter.QuestionAnswerAdapter;
import com.cays.myresearch.constant.Constant;
import com.cays.myresearch.entity.Question;
import com.cays.myresearch.entity.QuestionAnswer;
import com.cays.myresearch.entity.ResponseInfo;
import com.cays.myresearch.entity.Student;
import com.cays.myresearch.entity.UserInfo;
import com.cays.myresearch.ui.HeadControlPanel;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Response;

public class QuestionInfoActivity extends AppCompatActivity implements
    HeadControlPanel.HeadPanelCallback,View.OnClickListener,
        QuestionAnswerAdapter.QuestionAnswerItemClickListener {
    private HeadControlPanel questionInfoHeader;
    private Question intentQuestion;
    private TextView questionInfoName,questionInfoTime,questionInfoContent;
    private Button writeAnswerBtn,deleteBtn,changeBtn;
    private RecyclerView answerRv;
    private List<QuestionAnswer> answerList=new ArrayList<>();
    private QuestionAnswerAdapter questionAnswerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String intentQuestionStr=getIntent().getStringExtra("intent_question");
        intentQuestion=Constant.gson.fromJson(intentQuestionStr,new TypeToken<Question>(){}
            .getType());
        setContentView(R.layout.activity_question_info);
        if (getSupportActionBar()!=null){getSupportActionBar().hide();}
        initView();
        initAnswerList();
        addRead();
    }
    private void initView(){
        if(questionInfoHeader==null){
            questionInfoHeader=(HeadControlPanel)findViewById(R.id.question_info_header);
            questionInfoHeader.initHeadPanel();
            questionInfoHeader.setHeadPanelCallback(this);
        }
        questionInfoHeader.setLeftImage(R.drawable.ic_back);
        questionInfoHeader.setMiddleTitle("问题详细信息");
        questionInfoHeader.setRightTitle("");
        questionInfoName=(TextView)findViewById(R.id.question_info_name);
        questionInfoTime=(TextView)findViewById(R.id.question_info_time);
        questionInfoContent=(TextView)findViewById(R.id.question_info_content);
        writeAnswerBtn=(Button)findViewById(R.id.question_info_write_answer_btn);
        answerRv= (RecyclerView) findViewById(R.id.question_info_anwser_rv);
        writeAnswerBtn.setOnClickListener(this);
        deleteBtn=(Button)findViewById(R.id.question_info_delete_btn);
        deleteBtn.setOnClickListener(this);
        changeBtn=(Button)findViewById(R.id.question_info_change_btn);
        changeBtn.setOnClickListener(this);
        if(intentQuestion!=null){
            questionInfoName.setText(intentQuestion.getName());
            questionInfoTime.setText(intentQuestion.getTime());
            questionInfoContent.setText(intentQuestion.getContent());
        }
    }
    private void initAnswerList(){
        answerList.clear();
        refreshQuestionAnswer();
        GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),1);
        answerRv.setLayoutManager(gridLayoutManager);
        questionAnswerAdapter=new QuestionAnswerAdapter(answerList);
        answerRv.setAdapter(questionAnswerAdapter);
        questionAnswerAdapter.setQuestionAnswerItemClickListener(this);
    }
    private void refreshQuestionAnswer(){
        if (intentQuestion==null)return;
        final String url=Constant.URL+"question/question_answer_list";
        final MultipartBody.Builder builder=new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("question",Constant.gson.toJson(intentQuestion));
        HttpUtil.sendHttpRequest(url,builder,handler,2,0);
    }
    private void addRead(){
        if (intentQuestion==null)return;
        final String url=Constant.URL+"question/add_read";
        final MultipartBody.Builder builder=new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("question",Constant.gson.toJson(intentQuestion));
        HttpUtil.sendHttpRequest(url,builder,handler,3,0);
    }
    @Override
    public void onHeadPanelClick(int itemId) {
        switch (itemId){
            case Constant.btn_left_title:
                finish();
                break;
            case Constant.btn_middle_title:
                break;
            case Constant.btn_right_title:
                break;
            default:break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.question_info_write_answer_btn:
                Intent intent=new Intent(this,PostQuestionActivity.class);
                String s1=Constant.gson.toJson(intentQuestion);
                intent.putExtra("write_answer",s1);
                startActivity(intent);
                finish();
                break;
            case R.id.question_info_delete_btn:deleteQuestion(intentQuestion);break;
            case R.id.question_info_change_btn:
                changeQuestion(intentQuestion);
                break;
            default:break;
        }
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.what==0){
                Toast.makeText(getApplicationContext(),"未知错误",Toast.LENGTH_SHORT).show();
            }else if(msg.what==1){
                String s=(String) msg.obj;
                ResponseInfo responseInfo=Constant.gson.fromJson(s,
                        new TypeToken<ResponseInfo>(){}.getType());
                Toast.makeText(getApplicationContext(),
                        responseInfo.getResponseInfo(), Toast.LENGTH_SHORT).show();
                if (responseInfo.getResponseCode()==200)finish();
            }else if (msg.what==2){
                String s=(String)msg.obj;
                if (s.contains("~")) {
                    String s1 = s.split("~")[1];
                    List<QuestionAnswer> answers = Constant.gson.fromJson(s1,
                            new TypeToken<List<QuestionAnswer>>() {
                            }.getType());
                    answerList.clear();
                    answerList.addAll(answers);
                    questionAnswerAdapter.notifyDataSetChanged();
                }
                Toast.makeText(getApplicationContext(),"更新成功",
                        Toast.LENGTH_SHORT).show();
            }else if(msg.what==3){
                String s=(String) msg.obj;
                if (s==null||s.isEmpty())return false;
                ResponseInfo responseInfo=Constant.gson.fromJson(s,
                        new TypeToken<ResponseInfo>(){}.getType());
                Toast.makeText(getApplicationContext(),
                        responseInfo.getResponseInfo(), Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    });
    private void deleteQuestion(Question question){
        LoginAction loginAction=new LoginAction();
        if (!loginAction.hasUserInfo(getApplicationContext())){
            Toast.makeText(this,"未登录",Toast.LENGTH_SHORT).show();
            return;
        }
        UserInfo userInfo=loginAction.getUserInfo(getApplicationContext());
        if (userInfo.getType()!=Constant.user_student){
            Toast.makeText(this,"用户不是学生",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!userInfo.getName().equals(question.getName())){
            Toast.makeText(this,"不是作者无权删除",Toast.LENGTH_SHORT).show();
            return;
        }
        final String url=Constant.URL+"question/delete";
        final MultipartBody.Builder builder=new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("delete_question",Constant.gson.toJson(question));
        HttpUtil.sendHttpRequest(url,builder,handler,1,0);
    }
    private void changeQuestion(Question question){
        Intent intent2=new Intent(this,PostQuestionActivity.class);
        String s12=Constant.gson.toJson(question);
        intent2.putExtra("change_question",s12);
        startActivity(intent2);
        finish();
    }

    @Override
    public void questionAnswerItemClick(List<QuestionAnswer> answers, int position) {

    }
}
